<template>
  <div class="supplier-edit-container">
    <!-- 页面标题和操作区 -->
    <div class="page-header">
      <el-button type="default" icon="ArrowLeft" @click="handleBack">返回列表</el-button>
      <h1>编辑供应商</h1>
    </div>

    <!-- 表单卡片 -->
    <el-card class="form-card">
      <el-form
        ref="supplierFormRef"
        :model="supplierForm"
        :rules="formRules"
        label-width="120px"
        class="supplier-form"
        v-loading="loading"
      >
        <!-- 基本信息区域 -->
        <el-divider content-position="left">基本信息</el-divider>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="供应商编码" prop="code">
              <el-input v-model="supplierForm.code" placeholder="供应商编码" readonly>
                <template #prefix><Lock /></template>
              </el-input>
              <div class="form-hint">编码不可修改</div>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="供应商名称" prop="name">
              <el-input v-model="supplierForm.name" placeholder="请输入供应商名称" maxlength="100"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="统一社会信用代码" prop="creditCode">
              <el-input v-model="supplierForm.creditCode" placeholder="请输入统一社会信用代码" maxlength="18"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="成立日期" prop="establishDate">
              <el-date-picker
                v-model="supplierForm.establishDate"
                type="date"
                placeholder="选择成立日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
              ></el-date-picker>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="注册资本(万元)" prop="registeredCapital">
              <el-input v-model.number="supplierForm.registeredCapital" placeholder="请输入注册资本" type="number"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="企业类型" prop="enterpriseType">
              <el-select v-model="supplierForm.enterpriseType" placeholder="请选择企业类型">
                <el-option label="有限责任公司" value="有限责任公司"></el-option>
                <el-option label="股份有限公司" value="股份有限公司"></el-option>
                <el-option label="个体工商户" value="个体工商户"></el-option>
                <el-option label="合伙企业" value="合伙企业"></el-option>
                <el-option label="其他" value="其他"></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="所属行业" prop="industry">
              <el-select v-model="supplierForm.industry" placeholder="请选择所属行业">
                <el-option label="批发和零售业" value="批发和零售业"></el-option>
                <el-option label="信息传输、软件和信息技术服务业" value="信息传输、软件和信息技术服务业"></el-option>
                <el-option label="制造业" value="制造业"></el-option>
                <el-option label="建筑业" value="建筑业"></el-option>
                <el-option label="金融业" value="金融业"></el-option>
                <el-option label="其他" value="其他"></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="经营范围" prop="businessScope">
              <el-input v-model="supplierForm.businessScope" placeholder="请输入经营范围" maxlength="500"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 联系信息区域 -->
        <el-divider content-position="left">联系信息</el-divider>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="联系人" prop="contactPerson">
              <el-input v-model="supplierForm.contactPerson" placeholder="请输入联系人" maxlength="50"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="联系电话" prop="contactPhone">
              <el-input v-model="supplierForm.contactPhone" placeholder="请输入联系电话" maxlength="20"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="电子邮箱" prop="email">
              <el-input v-model="supplierForm.email" placeholder="请输入电子邮箱" maxlength="100"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="邮政编码" prop="zipCode">
              <el-input v-model="supplierForm.zipCode" placeholder="请输入邮政编码" maxlength="6"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="省份" prop="provinceCode">
              <el-select v-model="supplierForm.provinceCode" placeholder="请选择省份" @change="handleProvinceChange">
                <el-option v-for="province in provinces" :key="province.code" :label="province.name" :value="province.code"></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="城市" prop="cityCode">
              <el-select v-model="supplierForm.cityCode" placeholder="请选择城市" :disabled="!supplierForm.provinceCode">
                <el-option v-for="city in cities" :key="city.code" :label="city.name" :value="city.code"></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="详细地址" prop="address">
              <el-input v-model="supplierForm.address" placeholder="请输入详细地址" maxlength="200"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="网站地址" prop="website">
              <el-input v-model="supplierForm.website" placeholder="请输入网站地址" maxlength="100"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 银行账户信息区域 -->
        <el-divider content-position="left">银行账户信息</el-divider>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="开户银行" prop="bankName">
              <el-input v-model="supplierForm.bankName" placeholder="请输入开户银行" maxlength="100"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="银行账号" prop="bankAccount">
              <el-input v-model="supplierForm.bankAccount" placeholder="请输入银行账号" maxlength="30"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="开户名" prop="accountName">
              <el-input v-model="supplierForm.accountName" placeholder="请输入开户名" maxlength="100"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="联行号" prop="bankCode">
              <el-input v-model="supplierForm.bankCode" placeholder="请输入联行号" maxlength="20"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 备注信息区域 -->
        <el-divider content-position="left">备注信息</el-divider>

        <el-form-item label="备注">
          <el-input
            v-model="supplierForm.remark"
            type="textarea"
            placeholder="请输入备注信息"
            :rows="4"
            maxlength="500"
          ></el-input>
        </el-form-item>

        <!-- 表单操作按钮 -->
        <el-form-item class="form-actions">
          <el-button type="primary" @click="handleSubmit">保存</el-button>
          <el-button @click="handleReset">重置</el-button>
          <el-button @click="handleBack">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ArrowLeft, Lock } from '@element-plus/icons-vue';
import { ElMessage, ElForm } from 'element-plus';

// 定义省份和城市接口
interface RegionItem {
  code: string;
  name: string;
}

// 定义供应商表单接口
interface SupplierForm {
  id: string;
  code: string;
  name: string;
  creditCode: string;
  establishDate: string;
  registeredCapital: number;
  enterpriseType: string;
  industry: string;
  businessScope: string;
  contactPerson: string;
  contactPhone: string;
  email: string;
  provinceCode: string;
  cityCode: string;
  address: string;
  zipCode: string;
  website: string;
  bankName: string;
  bankAccount: string;
  accountName: string;
  bankCode: string;
  remark?: string;
}

// 状态管理
const supplierFormRef = ref<InstanceType<typeof ElForm>>();
const loading = ref(true);
const route = useRoute();
const router = useRouter();
const supplierId = route.params.id as string;

// 供应商表单数据
const supplierForm = reactive<SupplierForm>({
  id: '',
  code: '',
  name: '',
  creditCode: '',
  establishDate: '',
  registeredCapital: 0,
  enterpriseType: '',
  industry: '',
  businessScope: '',
  contactPerson: '',
  contactPhone: '',
  email: '',
  provinceCode: '',
  cityCode: '',
  address: '',
  zipCode: '',
  website: '',
  bankName: '',
  bankAccount: '',
  accountName: '',
  bankCode: '',
  remark: ''
});

// 省份数据
const provinces = ref<RegionItem[]>([
  { code: '330000', name: '浙江省' },
  { code: '110000', name: '北京市' },
  { code: '310000', name: '上海市' },
  { code: '440000', name: '广东省' },
  { code: '510000', name: '四川省' },
  { code: '420000', name: '湖北省' }
]);

// 城市数据（模拟）
const cities = ref<RegionItem[]>([]);
const cityDataMap: Record<string, RegionItem[]> = {
  '330000': [
    { code: '330100', name: '杭州市' },
    { code: '330200', name: '宁波市' },
    { code: '330300', name: '温州市' },
    { code: '330400', name: '嘉兴市' }
  ],
  '110000': [
    { code: '110100', name: '北京市' }
  ],
  '310000': [
    { code: '310100', name: '上海市' }
  ],
  '440000': [
    { code: '440100', name: '广州市' },
    { code: '440300', name: '深圳市' },
    { code: '440600', name: '佛山市' }
  ]
};

// 表单验证规则
const formRules = reactive({
  name: [
    { required: true, message: '请输入供应商名称', trigger: 'blur' },
    { min: 2, max: 100, message: '供应商名称长度在 2 到 100 个字符', trigger: 'blur' }
  ],
  creditCode: [
    { required: true, message: '请输入统一社会信用代码', trigger: 'blur' },
    { pattern: /^[0-9A-HJ-NPQRTUWXY]{2}\d{6}[0-9A-HJ-NPQRTUWXY]{10}$/, message: '请输入有效的统一社会信用代码', trigger: 'blur' }
  ],
  establishDate: [
    { required: true, message: '请选择成立日期', trigger: 'change' }
  ],
  registeredCapital: [
    { required: true, message: '请输入注册资本', trigger: 'blur' },
    { type: 'number', min: 0, message: '注册资本不能为负数', trigger: 'blur' }
  ],
  enterpriseType: [
    { required: true, message: '请选择企业类型', trigger: 'change' }
  ],
  industry: [
    { required: true, message: '请选择所属行业', trigger: 'change' }
  ],
  contactPerson: [
    { required: true, message: '请输入联系人', trigger: 'blur' },
    { max: 50, message: '联系人长度不能超过 50 个字符', trigger: 'blur' }
  ],
  contactPhone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号码', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入电子邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入有效的电子邮箱', trigger: 'blur' }
  ],
  provinceCode: [
    { required: true, message: '请选择省份', trigger: 'change' }
  ],
  cityCode: [
    { required: true, message: '请选择城市', trigger: 'change' }
  ],
  address: [
    { required: true, message: '请输入详细地址', trigger: 'blur' },
    { max: 200, message: '详细地址长度不能超过 200 个字符', trigger: 'blur' }
  ],
  bankName: [
    { required: true, message: '请输入开户银行', trigger: 'blur' },
    { max: 100, message: '开户银行长度不能超过 100 个字符', trigger: 'blur' }
  ],
  bankAccount: [
    { required: true, message: '请输入银行账号', trigger: 'blur' },
    { max: 30, message: '银行账号长度不能超过 30 个字符', trigger: 'blur' }
  ],
  accountName: [
    { required: true, message: '请输入开户名', trigger: 'blur' },
    { max: 100, message: '开户名长度不能超过 100 个字符', trigger: 'blur' }
  ]
});

// 省份变化时更新城市列表
const handleProvinceChange = (code: string) => {
  supplierForm.cityCode = '';
  cities.value = cityDataMap[code] || [];
};

// 返回供应商列表
const handleBack = () => {
  router.push({ name: 'SupplierList' });
};

// 重置表单
const handleReset = async () => {
  await nextTick();
  supplierFormRef.value?.resetFields();
};

// 提交表单
const handleSubmit = async () => {
  if (!supplierFormRef.value) return;

  try {
    await supplierFormRef.value.validate();
    loading.value = true;

    // 模拟API请求
    await new Promise(resolve => setTimeout(resolve, 1500));

    ElMessage.success('供应商更新成功');
    router.push({ name: 'SupplierList' });
  } catch (error) {
    if (typeof error === 'string') {
      ElMessage.error(error);
    } else {
      console.error('表单验证失败:', error);
    }
  } finally {
    loading.value = false;
  }
};

// 获取供应商详情数据
const fetchSupplierDetail = async () => {
  try {
    // 模拟API请求
    await new Promise(resolve => setTimeout(resolve, 1000));

    // 生成模拟数据
    const provinceCode = ['330000', '110000', '310000', '440000'][Math.floor(Math.random() * 4)];
    const provinceName = provinces.value.find(p => p.code === provinceCode)?.name || '';
    const cityList = cityDataMap[provinceCode] || [];
    const city = cityList[Math.floor(Math.random() * cityList.length)] || { code: '', name: '' };

    // 填充表单数据
    Object.assign(supplierForm, {
      id: supplierId,
      code: `SP${Math.floor(Math.random() * 10000).toString().padStart(6, '0')}`,
      name: `供应商${Math.floor(Math.random() * 1000) + 1}`,
      creditCode: `91${Math.floor(Math.random() * 100000000000000000).toString().padStart(17, '0')}`,
      establishDate: new Date(2000 + Math.floor(Math.random() * 20), Math.floor(Math.random() * 12), Math.floor(Math.random() * 28)).toISOString().slice(0, 10),
      registeredCapital: Math.floor(Math.random() * 10000) + 100,
      enterpriseType: ['有限责任公司', '股份有限公司', '个体工商户', '合伙企业'][Math.floor(Math.random() * 4)],
      industry: ['批发和零售业', '信息传输、软件和信息技术服务业', '制造业', '建筑业'][Math.floor(Math.random() * 4)],
      businessScope: ['办公用品销售；计算机软硬件及辅助设备零售；电子产品销售；家具销售；日用百货销售；五金产品零售', '信息技术咨询服务；软件开发；数据处理服务；计算机系统服务；互联网信息服务'][Math.floor(Math.random() * 2)],
      contactPerson: `联系人${Math.floor(Math.random() * 100)}`,
      contactPhone: `13${Math.floor(Math.random() * 100000000).toString().padStart(8, '0')}`,
      email: `contact${Math.floor(Math.random() * 1000)}@example.com`,
      provinceCode,
      cityCode: city.code,
      address: `测试地址${Math.floor(Math.random() * 100)}号`,
      zipCode: `${Math.floor(Math.random() * 1000000).toString().padStart(6, '0')}`,
      website: `http://www.supplier${Math.floor(Math.random() * 1000)}.com`,
      bankName: ['中国工商银行', '中国建设银行', '中国银行', '中国农业银行'][Math.floor(Math.random() * 4)] + `${Math.floor(Math.random() * 100)}支行`,
      bankAccount: `6222${Math.floor(Math.random() * 1000000000000).toString().padStart(12, '0')}`,
      accountName: `供应商${Math.floor(Math.random() * 1000) + 1}`,
      bankCode: `${Math.floor(Math.random() * 1000000).toString().padStart(12, '0')}`,
      remark: Math.random() > 0.5 ? '这是一个测试供应商，用于系统演示。' : undefined
    });

    // 设置城市列表
    cities.value = cityList;
  } catch (error) {
    ElMessage.error('获取供应商详情失败');
    console.error('获取供应商详情失败:', error);
  } finally {
    loading.value = false;
  }
};

// 页面加载时获取数据
onMounted(() => {
  fetchSupplierDetail();
});
</script>

<style scoped lang="scss">
.supplier-edit-container {
  padding: 0 20px;
}

.page-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  gap: 15px;
}

.form-card {
  margin-bottom: 20px;
}

.supplier-form {
  padding: 10px 0;
}

.el-divider--horizontal {
  margin: 25px 0;
}

.form-hint {
  color: #909399;
  font-size: 12px;
  margin-top: 5px;
}

.form-actions {
  display: flex;
  justify-content: center;
  gap: 15px;
  margin-top: 30px;
}

/* 适配小屏幕 */
@media (max-width: 768px) {
  .supplier-edit-container {
    padding: 0 10px;
  }

  .el-col {
    flex: 0 0 100%;
    max-width: 100%;
  }
}
</style>